#include <stdio.h>  
#include <stdbool.h>  
#include <stdint.h>  
#include <malloc.h>  
#include <unistd.h>  
#include <stdlib.h>  
#include <string.h>  
#include <getopt.h>  
#include <fcntl.h>  
#include <ctype.h>  
#include <errno.h>  
#include <limits.h>  
#include <time.h> 
#include <locale.h>  
#include <signal.h>  
#include <pthread.h>
#include <sys/unistd.h>  
#include <sys/stat.h>  
#include <sys/types.h>  
#include <sys/socket.h>
#include <sys/mman.h>
#include <linux/input.h>
#include <linux/fb.h>
#include <arpa/inet.h>
#include <termios.h> 

/*
	Init_TcpSock:初始化TCP套接字
*/
int Init_TcpSock(void)
{
	//创建套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1)
	{
		perror("创建套接字失败");
		return -1;
	}

	//IP地址以及端口号可以复用
	int on = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(1));

	//绑定自身IP地址
	struct sockaddr_in sin;
	bzero((char *)&sin,sizeof(sin));
	sin.sin_family = AF_INET;
	//sin.sin_addr.s_addr = htonl("192.168.1.100");	
	inet_pton(AF_INET,"192.168.31.27",&sin.sin_addr);  //IP地址必须与服务器真实的IP地址一致
	sin.sin_port = htons(6666);
	int ret = bind(sockfd, (struct sockaddr *)&sin, sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind() failed");
		exit(0);
	}

	//监听套接字
	listen(sockfd,3);

	printf("wait for connecting ... \n");
	socklen_t addrlen = sizeof(struct sockaddr);
    int sockfd_asr = -1;
	while(1)
	{		
		sockfd_asr = accept(sockfd, (struct sockaddr *)&sin, &addrlen);
		if(sockfd_asr < 0)
		{
			if(errno == EINTR)
				continue;
			perror("accpet()");
			exit(1);
		}
		else
			break;
	}
	
	printf("new connection: %s: %hu \n", inet_ntoa(sin.sin_addr),ntohs(sin.sin_port));
	
	return sockfd_asr;
}

int main()
{
	int sockfd = Init_TcpSock();

	while(1)
	{
		unsigned char buf[512] = {0};
		int ret = read(sockfd,buf,512);//接收客户端发送过来的数据
		if(ret == -1)
		{
			perror("读取客户端失败!\n");
			continue;
		}

		printf("%s\n",buf);
	}


#if 0	
    //1.初始化套接字
    int sockfd = Init_TcpSock();
      int k=1;
    while(1)
    {
    	int sum=0;
        unsigned char flag[512] = {0};
        //2.等待客户端发送过来的数据
        //int ret = read(sockfd,sum,sizeof(sum));
        // int ret = read(sockfd,buf,sizeof(buf));
		int ret = read(sockfd,flag,sizeof(flag));
        if(ret == -1)
        {
            perror("服务器接收失败");
            return -1;
        }
        printf("宫保鸡丁:%c份,红扒鸡翅:%c份,红槽排骨:%c份,红烧牛蛙:%c份,毛血旺:%c份,梅菜扣肉:%c份\t\n",flag[0],flag[1],flag[2],flag[3],flag[4],flag[5]);
        printf("\n");
		printf("清炒时蔬:%c份,清江烤鱼:%c份,软酥炸鸡:%c份,三鲜汤:%c份,山药炖鸡:%c份,蒜蓉虾球:%c份\t\n",flag[6],flag[7],flag[8],flag[9],flag[10],flag[11]);
		printf("\n");
		printf("锡纸烤鸭:%c份,一锅鲜：%c份,油焖大虾:%c份,玉带虾仁:%c份,长沙臭豆腐:%c份",flag[12],flag[13],flag[14],flag[15],flag[16]);
        printf("\n");
		printf("章若楠:已售罄\t\n");
		usleep(100000);
        unsigned char buf1[128] = {"接收成功,进行结算!"};
        //3.给客户端回应
        ret = write(sockfd,buf1,strlen(buf1));
        if(ret == -1)
        {
            perror("服务器发送失败");
            return -1;
        }
    }
#endif 
}